<script>
import WithDialog from '@/components/WithDialog/withDialog'
import { getConferenceRoomList, checkReservationTime } from '@/api/conferenceRoom'
import UserSelectModal from '@/components/UserSelectModal/UserSelectModal.vue'
import { cloneDeep } from 'lodash-es'

export default {
  name: 'ReserveEdit',
  components: {
    WithDialog,
    UserSelectModal
  },
  props: {
    value: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: false
    },
    confirmLoading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      rules: {
        conference_room_id: [{ required: true, message: '请选择会议室', trigger: 'change' }],
        start_time: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请选择开始时间'))
              } else if (this.form.end_time && new Date(value) >= new Date(this.form.end_time)) {
                callback(new Error('开始时间必须早于结束时间'))
              } else {
                callback()
              }
            },
            trigger: 'change' }
        ],
        end_time: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请选择结束时间'))
              } else if (this.form.start_time && new Date(value) <= new Date(this.form.start_time)) {
                callback(new Error('结束时间必须晚于开始时间'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        reason: [{ required: true, message: '请输入预约原因', trigger: 'blur' }]
      },
      loading: false,
      roomList: [],
      userModalVisible: false,
      conflictRecord: [],
      conflictDialogVisible: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },

    isCurrentRecord() {
      return this.conflictRecord.length === 1 && this.conflictRecord[0].id === this.form.id
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.form = { ...val }
        }
      },
      immediate: true
    },
    dialogVisible(val) {
      if (val) {
        this.init()
      }
    }
  },
  methods: {
    async handleConfirm() {
      if (this.conflictRecord.length && !this.isCurrentRecord) {
        this.$message.error('存在时间冲突的预约记录，请修改时间后重试')
        this.conflictDialogVisible = true
        return
      }
      try {
        await this.$refs.form.validate()
        const data = cloneDeep(this.form)
        const users = data.users

        data.users = users.length ? JSON.stringify(users) : null
        this.$emit('confirm', data)
      } catch (error) {
        console.error('表单验证失败', error)
      }
    },
    handleCancel() {
      this.$emit('update:visible', false)
    },
    resetFields() {
      this.$refs.form?.resetFields()
    },

    async init() {
      this.loading = true

      await Promise.allSettled([
        this.getRoomList()
      ])

      this.loading = false
    },

    async getRoomList() {
      try {
        const res = await getConferenceRoomList()
        console.log('res --------->', res)
        this.roomList = res.data.filter(item => item.state)
          .map(item => ({
            label: item.name,
            value: item.id
          }))
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      }
    },

    async checkTimeConflict() {
      try {
        const { conference_room_id, start_time, end_time } = this.form
        const res = await checkReservationTime({ conference_room_id, start_time, end_time })
        this.conflictRecord = []
        this.conflictDialogVisible = false
      } catch (error) {
        this.conflictRecord = error?.response?.data?.data

        if (!this.isCurrentRecord && this.conflictRecord?.length > 0) {
          this.conflictDialogVisible = true
          this.$message.error(error?.response?.data?.message)
        }
      }
    },

    handleRoomChange() {
      this.checkTimeConflict()
    },

    handleTimeChange() {
      this.checkTimeConflict()
    },

    handleOpenUserSelect() {
      this.userModalVisible = true
    }
  }
}
</script>

<template>
  <div>
    <WithDialog
      :visible.sync="dialogVisible"
      title="编辑会议预约"
      :close-on-click-modal="false"
      :confirm-btn-loading="confirmLoading"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    >
      <el-form
        ref="form"
        v-loading="loading"
        :model="form"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item
          label="会议室"
          prop="conference_room_id"
        >
          <el-select
            v-model="form.conference_room_id"
            placeholder="请选择会议室"
            @change="handleRoomChange"
          >
            <el-option
              v-for="(item, index) in roomList"
              :key="index"
              :label="item?.label"
              :value="item?.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="开始时间"
          prop="start_time"
        >
          <el-date-picker
            v-model="form.start_time"
            type="datetime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="{
              disabledDate: time => time.getTime() < Date.now() - 8.64e7
            }"
            @change="handleTimeChange"
          />
        </el-form-item>

        <el-form-item
          label="结束时间"
          prop="end_time"
        >
          <el-date-picker
            v-model="form.end_time"
            type="datetime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="{
              disabledDate: time => time.getTime() < Date.now() - 8.64e7
            }"
            @change="handleTimeChange"
          />
        </el-form-item>

        <el-form-item
          label="预约原因"
          prop="reason"
        >
          <el-input
            v-model="form.reason"
            placeholder="请输入预约原因"
          />
        </el-form-item>

        <el-form-item
          label="备注"
          prop="notes"
        >
          <el-input
            v-model="form.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>

        <el-form-item
          label="通知参会人"
          prop="users"
        >
          <el-button type="text" @click="handleOpenUserSelect">
            {{ form.users?.length ? `已选择${form.users?.length}人` : '选择需要通知的参会人' }}
          </el-button>
        </el-form-item>
      </el-form>
    </WithDialog>

    <UserSelectModal
      v-model="form.users"
      :visible.sync="userModalVisible"
      modal-append-to-body
    />

    <el-dialog
      title="预约时间冲突提醒"
      :visible.sync="conflictDialogVisible"
      z-index="9999"
      modal-append-to-body
      width="600px"
    >
      <div v-for="(item, index) in conflictRecord.filter(record => record.id !== form.id)" :key="index" class="conflict-item">
        <p><strong>会议室：</strong>{{ (() => {
          try {
            const roomData = JSON.parse(item.room);
            return roomData.name;
          } catch (e) {
            return '未知会议室';
          }
        })() }}</p>
        <p><strong>预约时间：</strong>{{ item.start_time }} 至 {{ item.end_time }}</p>
        <p><strong>预约原因：</strong>{{ item.reason }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.conflict-item {
  padding: 15px;
  border-bottom: 1px solid #EBEEF5;
  &:last-child {
    border-bottom: none;
  }
  p {
    margin: 8px 0;
  }
}
</style>
